<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Order;
use EasyWeChat\Factory;
use App\Models\User;
use Carbon\Carbon;
use App\Models\ReceivingAddres;
use Illuminate\Support\Facades\Auth;
use EasyWeChat\Foundation\Application;
use function EasyWeChat\Kernel\Support\generate_sign;

class OrderController extends Controller
{
   // public static  $order_number;

 public function dizhi(Request $request)
 {

     $dizhi_id = $request->input('id');
     $data = ReceivingAddres::where('id',$dizhi_id)->get();
     return $data;

 }
 public function placeManyOrder(Request $request)
 {
    $data = $request->all();
    // $code = $request->input('jsCode');
    // $miniProgram = \EasyWeChat::miniProgram();
    // $app = $miniProgram->auth->session($code);
    // $openid = $app['openid'];
    $openid = $request->input('openid');//ok
    $user = User::where('openid', $openid)->get()->toArray();
    $user_id =$user[0]['id'];
    $user_name =$user[0]['name'];
    $img = $request->input('img');
    $phone_number = $request->input('phone_number');
    $name = $request->input('name');
    $commodity_id = $request->input('commodity_id');//ok
    $commodity_name = $request->input('commodity_name');//ok
    $commodity_series_id = $request->input('commodity_series_id');
    $commodity_series_name = $request->input('commodity_series_name');//ok
    $total_price = $request->input('total_price');//ok
    $receiving_address = $request->input('receiving_address');//ok
    $leaving_message = $request->input('leaving_message');//ok\
    // self::$order_number =date("YmdHis");
    $order_number = date("YmdHis");
    $config = [
   // 必要配置
   'app_id'             => 'wxaacc4d201a5f3f45',
   'mch_id'             => '1502791981',
   'key'                => 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88',   // API 密钥

   // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
   'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
   'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！

   'notify_url'         => 'https://beize.sdjfe.com/api/order/callback',     // 你也可以在下单时单独设置来想覆盖它
    ];
    $app = Factory::payment($config);
    $result = $app->order->unify([
    'body' => $commodity_name,
    // 'out_trade_no' => $order_number,
    'out_trade_no' => $order_number,
    'total_fee' => $total_price,//单位是 分  ,故*100 使单位变成元
    // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
    'notify_url' => 'https://beize.sdjfe.com/api/order/callback', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
    'trade_type' => 'JSAPI',
    'openid' => $openid,
    // 'openid' => 'osVxJ5BRtLPWB5F434PGwUA2KuQA',
]);

      //本地数据库订单入库 S
       $order = new Order;
       $order->total_price = $total_price;
       $order->order_number = $order_number;
       $order->user_id = $user_id;
       $order->phone_number = $phone_number;
       $order->name = $name;
       $order->img = $img;
       $order->leaving_message = $leaving_message;
       $order->receiving_address = $receiving_address;
       $order->user_name=$user_name;
       $order->commodity_id = $commodity_id;
       $order->commodity_name = $commodity_name;
       $order->commodity_series_name = $commodity_series_name;
       $order->commodity_series_id = $commodity_series_id;
       $order->save();
      //本地数据库订单入库 E


    // 如果成功生成统一下单的订单，那么进行二次签名
if ($result['return_code'] === 'SUCCESS') {
    // 二次签名的参数必须与下面相同
    // dd($result);
    $params = [
        'appId'     => 'wxaacc4d201a5f3f45',
        'timeStamp' => time(),
        'nonceStr'  => $result['nonce_str'],
        'package'   => 'prepay_id=' . $result['prepay_id'],
        'signType'  => 'MD5',
    ];

    // 预订单入库 S
    $order->package=$params['package'];
    $order->save();
    // 预订单入库 E

     $params['paySign'] = generate_sign($params, 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88');

     return $params;
  } else {
      return $result;
  }
 }

   //下单接口 (单个商品下单)
   public function placeOrder(Request $request)
   {

     // return $request->all();
     // $code = $request->input('jsCode');
     // $miniProgram = \EasyWeChat::miniProgram();
     // $app = $miniProgram->auth->session($code);
     // $openid = $app['openid'];
     $openid = $request->input('openid');
     $user = User::where('openid', $openid)->get()->toArray();
     $user_id =$user[0]['id'];
     $user_name =$user[0]['name'];
     $commodity_id = $request->input('commodity_id');
     $order_number = $request->input('order_number');
     $img = $request->input('img');
     $commodity_name = $request->input('commodity_name');
     $phone_number = $request->input('phone_number');
     $name = $request->input('name');
     $commodity_series_id = $request->input('commodity_series_id');
     $commodity_series_name = $request->input('commodity_series_name');
     $total_price = $request->input('total_price');//ok
     $receiving_address = $request->input('receiving_address');
     $leaving_message = $request->input('leaving_message');
     $order_number = date("YmdHis");

     //本地数据库订单入库 S
      $order = new Order();
      $order->commodity_id=$commodity_id;
      $order->total_price=$total_price;
      $order->img=$img;
      $order->user_name=$user_name;
      $order->user_id=$user_id;
      $order->phone_number = $phone_number;
      $order->name = $name;
      $order->order_number=$order_number;
      $order->commodity_name=$commodity_name;
      $order->commodity_series_id=$commodity_series_id;
      $order->commodity_series_name=$commodity_series_name;
      $order->leaving_message=$leaving_message;
      $order->receiving_address=$receiving_address;
      $order->save();
      // exit;
     //本地数据库订单入库 E

     $config = [
    // 必要配置
    'app_id'             => 'wxaacc4d201a5f3f45',
    'mch_id'             => '1502791981',
    'key'                => 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88',   // API 密钥

    // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
    'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
    'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！

    'notify_url'         => 'https://beize.sdjfe.com/api/order/callback',     // 你也可以在下单时单独设置来想覆盖它
     ];
// dd($commodity_name);

    $app = Factory::payment($config);
    $result = $app->order->unify([
    'body' => $commodity_name,
    // 'out_trade_no' => $order_number,
    'out_trade_no' => $order_number,
    'total_fee' => $total_price,
    // 'spbill_create_ip' => '123.12.12.123', // 可选，如不传该参数，SDK 将会自动获取相应 IP 地址
    'notify_url' => 'https://beize.sdjfe.com/api/order/callback', // 支付结果通知网址，如果不设置则会使用配置里的默认地址
    'trade_type' => 'JSAPI',
    'openid' => $openid,
    // 'openid' => 'osVxJ5BRtLPWB5F434PGwUA2KuQA',
]);




    // 如果成功生成统一下单的订单，那么进行二次签名
if ($result['return_code'] === 'SUCCESS') {
    // 二次签名的参数必须与下面相同
    // dd($result);
    $params = [
        'appId'     => 'wxaacc4d201a5f3f45',
        'timeStamp' => time(),
        'nonceStr'  => $result['nonce_str'],
        'package'   => 'prepay_id=' . $result['prepay_id'],
        'signType'  => 'MD5',
    ];

      // return $params['package'];exit;
      // 预订单入库 S
      $order->package=$params['package'];
      $order->save();
      // 预订单入库 E

     $params['paySign'] = generate_sign($params, 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88');
     return $params;
  } else {
      return $result;
  }
}

    // 我的订单返回
    public function list(Request $request)
    {
      // $code = $request->input('jsCode');
      // $miniProgram = \EasyWeChat::miniProgram();
      // $app = $miniProgram->auth->session($code);
      // $openid = $app['openid'];
      $openid = $request->input('openid');
      // $user = User::where('openid', 'osVxJ5PgJbpMgm_9lfRnCCewG4qI')->get()->toArray();
      // $user = User::where('openid', $openid)->get()->toArray();
      // $user = User::where('id', '>=',1)->get()->toArray()
      // ;
      $user_id =$user[0]['id'];
      // $user_id =1;
      $orders = Order::where('user_id', $user_id)->paginate(10);
      return $orders;
    }

    public function index()
    {
        $user = Auth::guard('api')->user();
        $user_id = $user->id;
        // $open_id = request()->open_id;
        $orders = Orders::where('user_id', $user_id)->get();
        return new OrderResource($orders);
    }

    // 下单
    public function store()
    {
        $user = Auth::guard('api')->user();
        $user_id = $user->id;
        // 传入参数
        // 系统计算参数
        $open_id = User::where('id', $user_id)->first()->open_id;
        $out_trade_no = date("YmdHis");

        // 统一下单
        $payment = \EasyWeChat::payment(); // 微信支付
        // $payment = app('wechat.payment');
        $order_result = $payment->order->unify([
            'body' => '抗震支架购买',
            'out_trade_no' => $out_trade_no,
            'total_fee' => 0.1,
            'trade_type' => 'JSAPI',
            'notify_url' => 'https://beize.sdjfe.com/api/order/callback',
            // 'openid' => $open_id,
            'openid' => 'osVxJ5PgJbpMgm_9lfRnCCewG4qI',
        ]);
        // 下单成功


        if ($order_result['result_code'] == "SUCCESS") {
          // 二次签名的参数必须与下面相同
      $params = [
          'appId'     => 'wxaacc4d201a5f3f45',
          'timeStamp' => time(),
          'nonceStr'  => $result['nonce_str'],
          'package'   => 'prepay_id=' . $result['prepay_id'],
          'signType'  => 'MD5',
      ];

      // config('wechat.payment.default.key')为商户的key
      $params['paySign'] = generate_sign($params, 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88');

      return $params;
  } else {
      return $result;
  }
}

    // 获取订单状态
    public function orderStatus()
    {
      $config = [
     // 必要配置
     'app_id'             => 'wxaacc4d201a5f3f45',
     'mch_id'             => '1502791981',
     'key'                => 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88',   // API 密钥
     // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
     // 'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
     // 'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
     // 'notify_url'         => 'https://beize.sdjfe.com/api/order/callback',     // 你也可以在下单时单独设置来想覆盖它
      ];

     $app = Factory::payment($config);
      $app = $app->order->queryByOutTradeNumber('20180507132709');
      // dd($app);
// self::$order_number 订单号

        $order = Order::where('order_number', '20180507132709')->first();
        if ($order) {
            // 同步查询订单状态
            // dd($app);
            // dd($app['return_code']);
            // 支付成功
            if ($app['return_code'] == 'SUCCESS' && $app['trade_state'] == 'SUCCESS') {
                $this->afterPayment($order);
                // dd($app);
            }
            return ['status' => $order->payment_status];
        } else {
            return response()->json([
                'message' => '订单不存在',
            ], 404);
        }
    }


    // 更新支付状态，更新订单状态以及  收益
    protected function afterPayment($order)
    {
      $order->payment_status = 1;//0未付款  1已付款
      // $order->pay_time = Carbon::now();//付款时间
      $order->save();
    }

    // 支付结果回调
    public function orderCallback()
    {
      $this->orderStatus();
      $config = [
     // 必要配置
     'app_id'             => 'wxaacc4d201a5f3f45',
     'mch_id'             => '1502791981',
     'key'                => 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88',   // API 密钥
     // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
     'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
     'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
     'notify_url'         => 'https://beize.sdjfe.com/api/order/callback',     // 你也可以在下单时单独设置来想覆盖它
      ];

     $app = Factory::payment($config);

      $app = $app->order->queryByOutTradeNumber("20180507132709");
      // dd($app);
      // dd($app['trade_state']);
    }

    //已经支付订单返回
    public function alreadyPaid(Request $request)
   {
     // $code = $request->input('jsCode');
     // $miniProgram = \EasyWeChat::miniProgram();
     // $app = $miniProgram->auth->session($code);
     // $openid = $app['openid'];
     $openid = $request->input('openid');
     $user = User::where('openid', $openid)->get()->toArray();
     $user_id =$user[0]['id'];
     // $user_id =1;
     $orders = Order::where('payment_status', 1)->paginate(10);
     return $orders;
   }

 //未支付订单
  public function unpaid(Request $request)
  {
    // $code = $request->input('jsCode');
    // $miniProgram = \EasyWeChat::miniProgram();
    // $app = $miniProgram->auth->session($code);
    // $openid = $app['openid'];
    $openid = $request->input('openid');
    $user = User::where('openid', $openid)->get()->toArray();
    $user_id =$user[0]['id'];
    // $user_id =1;
    $orders = Order::where('payment_status', 0)->paginate(10);
    return $orders;
  }

 //已发货订单
  public function alreadyShipped(Request $request)
  {
    // $code = $request->input('jsCode');
    // $miniProgram = \EasyWeChat::miniProgram();
    // $app = $miniProgram->auth->session($code);
    // $openid = $app['openid'];
    $openid = $request->input('openid');
    $user = User::where('openid', $openid)->get()->toArray();
    $user_id =$user[0]['id'];
    // $user_id =1;
    $orders = Order::where('delivery_status', 1)->paginate(10);
    return $orders;
  }

 //未发货订单
 public function unshippedDelivery(Request $request)
 {
   // $code = $request->input('jsCode');
   // $miniProgram = \EasyWeChat::miniProgram();
   // $app = $miniProgram->auth->session($code);
   // $openid = $app['openid'];
   $openid = $request->input('openid');
   $user = User::where('openid', $openid)->get()->toArray();
   $user_id =$user[0]['id'];
   // $user_id =1;
   $orders = Order::where('delivery_status', 0)->paginate(10);
   return $orders;
 }


   public function test(Request $request)
   {
     $package = $request->input('package');
      // $order = Order::where('package', "prepay_id=wx081202428322745562079f283797684912")->get()->toArray();
      $order = Order::where('package', $package)->get()->toArray();
      $order_number = $order[0]['order_number'];

     $config = [
    // 必要配置
    'app_id'             => 'wxaacc4d201a5f3f45',
    'mch_id'             => '1502791981',
    'key'                => 'gxbzsyyxgsgxbzsyyxgsgxbzsyyxgs88',   // API 密钥
    // 如需使用敏感接口（如退款、发送红包等）需要配置 API 证书路径(登录商户平台下载 API 证书)
    // 'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
    // 'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
    // 'notify_url'         => 'https://beize.sdjfe.com/api/order/callback',     // 你也可以在下单时单独设置来想覆盖它
     ];

     $app = Factory::payment($config);
     $app = $app->order->queryByOutTradeNumber($order_number);
     // dd($app);
       $order = Order::where('order_number', $order_number)->first();
       if ($order) {
         // dd($order);
           // 同步查询订单状态
           // dd($app['return_code']);
           // dd($app['return_code']);
           // 支付成功
           if ($app['return_code'] == 'SUCCESS' && $app['trade_state'] == 'SUCCESS') {
               $this->afterPayment($order);
           }
           return ['status' => $order->payment_status];
       } else {
           return response()->json([
               'message' => '订单不存在',
           ], 404);
       }
   }
}
